package io.renren.system.oss.controller;

import com.google.gson.Gson;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AliyunGroup;
import io.renren.common.validator.group.QcloudGroup;
import io.renren.common.validator.group.QiniuGroup;
import io.renren.common.validator.group.ZiGuangYunGroup;
import io.renren.system.oss.cloud.CloudStorageConfig;
import io.renren.system.oss.cloud.OSSFactory;
import io.renren.system.oss.entity.SysOssEntity;
import io.renren.system.oss.service.SysOssService;
import io.renren.system.sys.service.SysParamsService;
import io.renren.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * 【系统设置-文件上传】
 */
@RestController
@RequestMapping("sys/oss")
@Api(tags = "【系统设置-文件上传】")
public class SysOssController {
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private SysParamsService sysParamsService;

    //云存储配置KEY
    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;

    @GetMapping("page")
    @ApiOperation(value = "根据查询条件分页获取文件上传列表数据")
    @RequiresPermissions("sys:oss:all")
    public Result<PageData<SysOssEntity>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysOssEntity> page = sysOssService.page(params);
        return new Result<PageData<SysOssEntity>>().ok(page);
    }

    @GetMapping("info")
    @ApiOperation(value = "获取云存储配置信息")
    @RequiresPermissions("sys:oss:all")
    public Result<CloudStorageConfig> info() {
        CloudStorageConfig config = sysParamsService.getValueObject(KEY, CloudStorageConfig.class);
        return new Result<CloudStorageConfig>().ok(config);
    }

    @PostMapping
    @ApiOperation(value = "保存云存储配置信息")
    @LogOperation("保存云存储配置信息")
    @RequiresPermissions("sys:oss:all")
    public Result saveConfig(@RequestBody CloudStorageConfig config) {
        if (config.getType() == Constant.CloudService.QINIU.getValue()) {//校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {//校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {//校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        } else if (config.getType() == Constant.CloudService.ZiGuang.getValue()) {//校验腾讯云数据
            ValidatorUtils.validateEntity(config, ZiGuangYunGroup.class);
        }
        sysParamsService.updateValueByCode(KEY, new Gson().toJson(config));
        return new Result();
    }

    @PostMapping("upload")
    @ApiOperation(value = "上传文件")
    public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new Result<Map<String, Object>>().error(ErrorCode.UPLOAD_FILE_EMPTY);
        }
//        // 文件后缀校验
//        String[] suffixStr = new String[]{"PNG", "JPG", "JPEG", "BMP", "GIF", "XLSX", "XLS", "DOCX", "DOC", "PDF", "RAR", "ZIP", "7Z"};
//        List<String> suffixList = Arrays.asList(suffixStr);
//        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//        if (!suffixList.contains(suffix.toUpperCase())) {
//            return new Result<Map<String, Object>>().error("文件类型不支持上传");
//        }
//        //上传文件
//        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
//        String url = OSSFactory.build().uploadSuffix(file.getBytes(), extension);

        Long d = System.currentTimeMillis();
        String originalFilename = file.getOriginalFilename();
        //过滤特殊字符
        originalFilename = this.StringFilter(originalFilename);
        originalFilename = this.replaceSpecialStr(originalFilename);
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), originalFilename);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.insert(ossEntity);

        Map<String, Object> data = new HashMap<>(1);
        data.put("src", url);
        data.put("fileName", originalFilename);

        return new Result<Map<String, Object>>().ok(data);
    }

    @DeleteMapping
    @ApiOperation(value = "根据主键删除已上传的文件记录")
    @LogOperation("根据主键删除已上传的文件记录")
    @RequiresPermissions("sys:oss:all")
    public Result delete(@RequestBody Long[] ids) {
        sysOssService.deleteBatchIds(Arrays.asList(ids));
        return new Result();
    }

    /**
     * 清除掉所有特殊字符
     *
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    private String StringFilter(String str) throws PatternSyntaxException {
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',//[//]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符等
     *
     * @param str
     * @return
     */
    private String replaceSpecialStr(String str) {
        if (StringUtils.isNotEmpty(str)) {
            str = str.replaceAll("\\s*|\t|\r|\n", "");
        }
        return str;
    }
}
